// components/baojie/index.js
import { selectOrderType, helpTtile } from '../utils/enumType';
import { addOrder, uploadFile } from '../api/index';
import { store } from '../../store/index';
import { dogType, sexType, jiadianType, lajiType, baojieType, selectContentTag } from './helpers';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    addrData: null,
    contentTag: [ ],
    orderType: '',
    formData: {
      remark: '',
      content: '',
      price: 2,
      fileList: [],
      yuyueTime: '',
      fangwuSize: '',
      count: 1,
      totalPrice: 0
    },
    projectTypeList: [],
    fileList: [],
    baojieShow: false,
    activeType: '',
    helpTtile:helpTtile,
    checked:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options, 'options');
    this.setData({
      type: options.type,
      orderType: selectOrderType[options.type].split('')[0],
      contentTag: selectContentTag(options.type)
    })
  
    switch (options.type) {
      case 'baojie':
        this.setData({
          projectTypeList: baojieType,
          activeType: '198'
        })
        break;
      case 'laji':
        this.setData({
          projectTypeList: lajiType,
          activeType: '小袋'
        })
        break;
      case 'jiadian':
        this.setData({
          projectTypeList: jiadianType,
          activeType: '油烟机'
        })
        break;
      case 'liu':
        this.setData({
          projectTypeList: dogType,
          activeType: '小型犬'
        })
        case 'game':
          this.setData({
            projectTypeList: sexType,
            activeType: '不限'
          })
          break;
    }


    wx.setNavigationBarTitle({
      title: selectOrderType[options.type]
    })
  },
  onUnload() {
    store.updateSelectAddrData(null);
  },
  onShow() {

    console.log(store.selectAddrData, 'store.selectAddrData');
    if (store.selectAddrData) {
      this.setData({
        addrData: {
          ...store.selectAddrData
        }
      });
    }
  },
  goToSelectAddr() {
    wx.navigateTo({
      url: '/pages/me_content/location?type=1'
    })
  },
  onChange({ detail }) {
    // 需要手动对 checked 状态进行更新
    this.setData({ checked: detail });
  },

  handleTypeSelect(e) {
    console.log(e, 'eeeee');

    this.setData({
      activeType: e.currentTarget.dataset.type
    })
  },

  submitOrder() {
    console.log('submitOrder', this.data.addrData);
    if (!this.data.addrData && this.data.type !== 'game') {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return;
    }
    if (!this.data.formData.yuyueTime && (this.data.type === 'game' || this.data.type === 'beizi' || this.data.type === 'jiadian')) {
      wx.showToast({
        title: '请输入预约时间',
        icon: 'none'
      })
      return;
    }
    if (!this.data.formData.content && this.data.type !== 'baojie' && this.data.type !== 'laji' && this.data.type !== 'jiadian') {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return;
    }

    this.getAddOrder();

    console.log('submitOrder');
  },
  getAddOrder() {
    let data = {}
 
    console.log(this.data, 'this.data.type');
    // return

    // 添加时间转换的辅助函数
    const convertTime = (time) => {
      const date = new Date();
      date.setHours(date.getHours() + Number(time)); // 当前时间增加12小时
      return date.getFullYear() + '-' + 
             String(date.getMonth() + 1).padStart(2, '0') + '-' + 
             String(date.getDate()).padStart(2, '0') + ' ' +
             String(date.getHours()).padStart(2, '0') + ':' +
             String(date.getMinutes()).padStart(2, '0') + ':' +
             String(date.getSeconds()).padStart(2, '0');
    };

    switch (this.data.type) {
      case 'lin':
        data = {
          type: '邻里互助',
          helpContent: this.data.formData.content,
          mark: this.data.formData.remark,
          helpReward: this.data.formData.price,
          addrId: this.data.addrData.id,
          userAddr: this.data.addrData,
          totalPrice: this.data.formData.price
        }
        break;
      case 'liu':
        data = {
          type: '遛狗服务',
          dogType: this.data.activeType,
          dogDemand: this.data.formData.content,
          addrId: this.data.addrData.id,
          userAddr: this.data.addrData,
          dogReward: this.data.formData.price,
          totalPrice: this.data.formData.price
        }
        break;
        case 'game':
          data = {
            type: '游戏开黑',
            kaiheiDemand: this.data.formData.content,
            kaiheiSex: this.data.activeType,
            kaiheiJiaji: this.data.checked ? '是' : '否',
            kaiheiReward: this.data.formData.price,
            // addrId: this.data.addrData.id,
            // userAddr: this.data.addrData,
            totalPrice: this.data.formData.price
          }
          break;
        case 'shop':
          data = {
            type: '代买商品',
            wareList: this.data .formData.content,
            wareJiaji: this.data.checked ? '是' : '否',
            wareLowPrice: this.data.formData.price || 0,
            totalPrice: this.data.formData.price || 0,
            addrId: this.data.addrData.id,
            userAddr: this.data.addrData,
            // wareList，wareJiaji，wareLowPrice
          }
          break;
        case 'baojie':
          data = {
            // baojieType，yuyueTime，fangwuSize，imgList，mark，totalPrice
            type: '保洁服务',
            baojieType: this.data.projectTypeList.find(item => item.value === this.data.activeType).label,
            yuyueTime: convertTime(this.data.formData.yuyueTime),
            fangwuSize: this.data.formData.fangwuSize,  
            imgList: this.data.fileList[0],
            fileList: this.data.formData.fileList,
            mark: this.data.formData.remark,
            totalPrice:  this.data.activeType,
            addrId: this.data.addrData.id,
            userAddr: this.data.addrData,
          }
          break;
          case 'beizi':
            data = {
              type: '晒被子',
              beiziDemand: this.data.formData.content,
              beiziTime: convertTime(this.data.formData.yuyueTime),
              beiziCount: this.data.formData.count,
              addrId: this.data.addrData.id,
              userAddr: this.data.addrData,
              totalPrice: 5 
            }
            break;
            case 'laji':
              data = {
                type: '代扔垃圾',   
                lajiSize: this.data.activeType,
                lajiCount: this.data.formData.count,
                imgList: this.data.fileList[0],
                fileList: this.data.formData.fileList,
                totalPrice: 3 * this.data.formData.count,
                addrId: this.data.addrData.id,
                userAddr: this.data.addrData,
              }
              break;
            case 'jiadian':
              data = {
                type: '家电清洗',
                cleanType: this.data.activeType,
                cleanCount: this.data.formData.count,
                cleanTime: convertTime(this.data.formData.yuyueTime),
                imgList: this.data.fileList[0],
                fileList: this.data.formData.fileList,
                totalPrice: this.data.formData.totalPrice,
                addrId: this.data.addrData.id,
                mark: this.data.formData.remark,
                userAddr: this.data.addrData,
              }
            break;
    }


    store.updateOrderData(data);

    wx.redirectTo({
      url: '/pages/confirmOrder/index'
    });

    // addOrder(data).then(res => {
    //   wx.showToast({
    //     title: '下单成功',
    //     icon: 'success'
    //   })

    //   console.log(res, 'res');
    // })
  },
  handleContentTag(e) {
    const str = e.currentTarget.dataset.index;
    console.log(e, 'str');
    this.setData({
      [`formData.content`]: this.data.formData.content + str
    })
  },
  handleStepperChange(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      [`formData.${type}`]: e.detail
    })
  },
  handleInput(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      [`formData.${type}`]: e.detail.value
    })
  },
  afterRead(event){
    const { file } = event.detail;
    uploadFile({...file, file: file.url}).then(res => {
      console.log(res, 'resresresres');
      this.setData({ 
        formData: {
          ...this.data.formData,
          fileList: [...this.data.formData.fileList, file]
        },
        fileList: [...this.data.fileList, res],
        canSubmit: true 
      });

    });
  }

})